package com.atshiyou.Util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;


public class SqlSessionUtil {
    // ThreadLocal管理SQLSession
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;

    // 配置文件只加载一遍
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,"development2");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //打开session方法
    public static SqlSession getSession(){
        //类似于单例的模式，获取sqlsession对象
        SqlSession session = threadLocal.get();
        if(session==null){
            session = sqlSessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }

    //关闭session
    public static void closeSession(){
        SqlSession session = threadLocal.get();
        if(session!=null) {
            session.close();
            threadLocal.remove();//清除数据
        }
    }
}
